<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 面板区域 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>

        <!-- 表单区域 -->
        <div>
          <el-form
            :model="questionForm"
            :rules="questionFormRules"
            ref="questionFormRef"
            label-width="120px"
          >
            <!-- 学科 -->
            <el-form-item label="学科：" required>
              <el-select
                v-model="subjectID"
                placeholder="请选择"
                style="width:400px"
              >
                <el-option
                  v-for="item in subjectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 目录 -->
            <el-form-item label="目录：" required>
              <el-select
                v-model="catelogID"
                placeholder="请选择"
                style="width:400px"
              >
                <el-option
                  v-for="item in catelogList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 企业 -->
            <el-form-item label="企业：" required>
              <el-select
                v-model="enterpriseID"
                placeholder="请选择"
                style="width:400px"
              >
                <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.company"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 城市 -->
            <el-form-item label="城市：" required>
              <!-- province -->
              <el-select
                v-model="province"
                placeholder="请选择"
                style="width:198px"
                class="province"
              >
                <el-option
                  v-for="(item, index) in provincesList"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>

              <!-- city -->
              <el-select
                v-model="city"
                placeholder="请选择"
                style="width:198px"
              >
                <el-option
                  v-for="(item, index) in citysList"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 方向 -->
            <el-form-item label="方向：" required>
              <el-select
                v-model="direction"
                placeholder="请选择"
                style="width:400px"
              >
                <el-option
                  v-for="(item, index) in directionList"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 题型 -->
            <el-form-item label="题型：" required>
              <el-radio
                v-for="item in questionType"
                :key="item.value"
                v-model="questionTypeRadio"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-form-item>

            <!-- 难度 -->
            <el-form-item label="难度：" required>
              <el-radio
                v-for="item in difficulty"
                :key="item.value"
                v-model="difficultyRadio"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-form-item>

            <!-- 题干 -->
            <el-form-item label="题干：" required>
              <div
                id="question"
                class="question"
                @keyup="onQuestionChange"
              ></div>
              <!-- <el-button @click="onClick">获取</el-button> -->
            </el-form-item>

            <!-- 选项 -->
            <el-form-item
              v-if="questionTypeRadio !== 3"
              label="选项："
              style="margin-top:34px"
            >
              <!-- 单选 -->
              <div v-if="questionTypeRadio === 1">
                <div
                  v-for="(item, index) in optionsNum"
                  :key="index"
                  class="option_item"
                >
                  <el-radio
                    :label="item"
                    v-model="optionsRadio"
                    class="optionRadio"
                  >
                    {{ String.fromCharCode(64 + item) }}：
                  </el-radio>
                  <el-input
                    style="width:240px"
                    v-model="optionList[index].title"
                  ></el-input>

                  <!-- 图片上传 -->
                  <el-upload
                    class="avatar-uploader"
                    action="http://localhost:3000/upload"
                    :show-file-list="false"
                    :on-success="
                      (res, file, filelist) =>
                        handleAvatarSuccess(res, file, filelist, index)
                    "
                  >
                    <img
                      v-if="optionList[index].img"
                      :src="optionList[index].img"
                      class="avatar"
                    />
                    <span v-else class="avatar-uploader-text">上传图片</span>
                    <i
                      class="el-icon-error avatar-close"
                      @click="closeImage(index, $event)"
                    ></i>
                  </el-upload>
                </div>
              </div>

              <!-- 多选 -->
              <!-- <div v-else-if="questionTypeRadio === 2"> -->
              <el-checkbox-group v-else v-model="optionCheckList">
                <div
                  v-for="(item, index) in optionsNum"
                  :key="item"
                  style="margin-bottom: 20px"
                >
                  <el-checkbox
                    :label="String.fromCharCode(64 + item)"
                    @change="checkboxChange(index, $event)"
                  >
                    {{ String.fromCharCode(64 + item) }}：
                  </el-checkbox>
                  <el-input
                    style="width:240px"
                    v-model="optionList[index].title"
                  ></el-input>

                  <!-- 图片上传 -->
                  <el-upload
                    class="avatar-uploader"
                    action="http://localhost:3000/upload"
                    :show-file-list="false"
                    :on-success="
                      (res, file, filelist) =>
                        handleAvatarSuccess(res, file, filelist, index)
                    "
                  >
                    <img
                      v-if="optionList[index].img"
                      :src="optionList[index].img"
                      class="avatar"
                    />
                    <span v-else class="avatar-uploader-text">上传图片</span>
                    <i
                      class="el-icon-error avatar-close"
                      @click="closeImage(index, $event)"
                    ></i>
                  </el-upload>
                </div>
              </el-checkbox-group>
              <!-- </div> -->

              <el-button
                type="danger"
                icon="el-icon-plus"
                @click="addOption"
                :disabled="questionTypeRadio === 2 ? false : true"
                size="small"
                >增加选项与答案</el-button
              >
            </el-form-item>

            <!-- 解析视频 -->
            <el-form-item label="解析视频：">
              <el-input v-model="videoURL" style="width: 400px"></el-input>
            </el-form-item>

            <!-- 答案解析 -->
            <el-form-item label="答案解析：" required>
              <div id="answer" class="answer" @keyup="onAnswerChange"></div>
            </el-form-item>

            <!-- 题目备注 -->
            <el-form-item label="题目备注：">
              <el-input
                type="textarea"
                v-model="remarks"
                style="width:400px"
                :rows="4"
              ></el-input>
            </el-form-item>

            <!-- 试题标签 -->
            <el-form-item label="试题标签：">
              <!-- <el-select
                v-model="tags"
                placeholder="请选择试题标签"
                style="width: 400px"
              >
                <el-option
                  v-for="item in tagsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
              <el-select
                v-model="tags"
                multiple
                placeholder="请选择试题标签"
                style="width: 400px"
              >
                <el-option
                  v-for="item in tagsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 确认提交 -->
            <el-form-item>
              <el-button type="primary" @click="onSubmit">确认提交</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 表单区域 -->
      </el-card>
      <!-- /面板区域 -->
    </div>
  </div>
</template>

<script>
// 代码高亮
import 'highlight.js/styles/an-old-hope.css'
import hljs from 'highlight.js'
import { simple as simplesubject } from '@/api/hmmm/subjects'
import { simple as simpleCatelog } from '@/api/hmmm/directorys'
import { list as companysList } from '@/api/hmmm/companys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as tagList } from '@/api/hmmm/tags'
import {
  add as addQuestion,
  update as updateQuestion
} from '@/api/hmmm/questions'
// 引入quill富文本编辑器
import 'quill/dist/quill.snow.css'
import Quill from 'quill'
export default {
  name: 'QuestionsNew',
  data() {
    return {
      // 表单数据
      questionForm: {},
      // 验证规则
      questionFormRules: {
        // subject: [{ required: true, message: "学科为必填项", trigger: "blur" }],
        // catelog: [{ required: true, message: "目录为必填项", trigger: "blur" }],
        // enterprise: [
        //   { required: true, message: "企业为必填项", trigger: "blur" }
        // ],
        // provinces: [
        //   { required: true, message: "城市为必填项", trigger: "blur" }
        // ],
        // direction: [
        //   { required: true, message: "方向为必填项", trigger: "blur" }
        // ],
        // questionType: [
        //   { required: true, message: "题型为必填项", trigger: "blur" }
        // ],
        // difficulty: [
        //   { required: true, message: "难度为必填项", trigger: "blur" }
        // ],
        // question: [
        //   { required: true, message: "题干为必填项", trigger: "blur" }
        // ],
        // answer: [
        //   { required: true, message: "答案解析为必填项", trigger: "blur" }
        // ]
      },
      optionsNum: 4, // 选项个数
      // 学科数据
      subjectList: [],
      // 目录数据
      catelogList: [],
      // 企业列表
      companyList: [],
      // 方向列表
      directionList: direction,
      // 城市
      provincesList: provinces(),
      // 地区
      citysList: [],
      // 题型
      questionType,
      // 试题标签列表
      tagsList: [],
      // 难度
      difficulty,
      subjectID: '', // 学科
      catelogID: '', // 目录
      enterpriseID: '', // 企业
      direction: '', // 方向
      province: '', // 城市
      city: '', // 地区
      questionTypeRadio: 1, // 题型
      difficultyRadio: 1, // 难度
      optionsRadio: null, // 选项选中项
      optionCheckList: [], // 复选框选中列表
      videoURL: '', // 解析视频
      answer: '', // 答案解析
      remarks: '', // 题目备注
      tags: [], // 试题标签
      question: '', // 题干
      optionList: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }
      ],
      imageUrl: [],
      data: {}
    }
  },
  created() {
    // 获取学科数据
    this.loadSubject()
    // 获取公司数据
    this.loadCompany()
    // 获取标签数据
    this.loadtags()
    try {
      const data = this.$route.params.id
      this.subjectID = data.subjectID
      this.catelogID = data.catelogID
      this.enterpriseID = data.enterpriseID
      this.province = data.province
      this.city = data.city
      this.direction = data.direction
      this.questionTypeRadio = data.questionType - 0
      this.difficultyRadio = data.difficulty - 0
      this.optionList = data.options
      for (let i = 0; i < data.options.length; i++) {
        if (data.questionType == 2) {
          data.options[i].isRight
            ? this.optionCheckList.push(data.options[i].code)
            : ''
        } else if (data.questionType == 1) {
          data.options[i].isRight ? (this.optionsRadio = i + 1) : ''
        }
      }
      this.videoURL = data.videoURL
      this.remarks = data.remarks
      this.tags.push(data.tags)
      this.answer = data.answer
      //
      this.question = data.question
    } catch (err) {
      console.log('真好')
    }
  },
  watch: {
    subjectID: function() {
      this.loadCatelog()
      this.loadtags()
    },
    province() {
      this.getCitysList()
    },

    // 监听单选
    optionsRadio() {
      for (let i = 0; i < this.optionList.length; i++) {
        this.optionList[i].isRight = false
      }
      this.optionList[this.optionsRadio - 1].isRight = !this.optionList[
        this.optionsRadio - 1
      ].isRight
    }
  },
  methods: {
    // 获取学科数据
    async loadSubject() {
      try {
        const { data } = await simplesubject()
        this.subjectList = data
        // 获取目录数据
        this.loadCatelog()
      } catch (err) {
        console.log('xxx', err)
      }
    },

    // 获取目录数据
    async loadCatelog() {
      try {
        const { data } = await simpleCatelog({ subjectID: this.subjectID })
        console.log(data)
        this.catelogList = data
      } catch (err) {
        console.log('数据获取失败', err)
      }
    },

    // 获取公司数据
    async loadCompany() {
      try {
        const { data } = await companysList({ pagesize: 5000 })
        console.log(data)
        this.companyList = data.items
      } catch (err) {
        console.log('获取公司数据失败', err)
      }
    },

    // 获取地区列表
    async getCitysList() {
      this.citysList = await citys(this.province)
      console.log(this.citysList)
    },

    // 获取标签列表
    async loadtags() {
      try {
        const { data } = await tagList({ subjectID: this.subjectID })
        // console.log(data, 111);
        this.tagsList = data
        console.log(data, 111)
      } catch (err) {
        console.log('获取标签数据失败', err)
      }
    },

    // 获取题干文本
    onQuestionChange() {
      this.question = this.quills1.getText()
      // console.log(this.quills1.getText());
    },

    // 获取答案解析文本
    onAnswerChange() {
      this.answer = this.quills2.getText()
      console.log(this.quills2.getText())
    },

    // 添加选项
    addOption() {
      this.optionsNum++
      this.optionList.push({
        code: '',
        title: '',
        img: '',
        isRight: false
      })
    },

    // 监听复选框的变化
    checkboxChange(index, e) {
      // console.log(index, e);
      this.optionList[index].isRight = e
      // this.optionList[index].code = this.optionCheckList[
      //   this.optionCheckList.length - 1
      // ];
    },

    // 提交
    async onSubmit() {
      const submitInfo = {
        subjectID: this.subjectID,
        catalogID: this.catelogID,
        enterpriseID: this.enterpriseID,
        province: this.province,
        city: this.city,
        direction: this.direction.toString(),
        questionType: this.questionTypeRadio.toString(),
        difficulty: this.difficultyRadio.toString(),
        question: this.question,
        options: this.optionList,
        videoURL: this.videoURL,
        answer: this.answer,
        remarks: this.remarks,
        tags: this.tags.join(',')
      }

      try {
        if (this.$route.params.id) {
          submitInfo.id = this.$route.params.id.id
          const { data } = await updateQuestion(submitInfo)
          console.log(data)
          this.$message.success('修改成功')
        } else {
          const { data } = await addQuestion(submitInfo)
          console.log(data)
          this.$message.success('提交成功')
        }
        this.$router.replace('/questions/list')
      } catch (err) {
        this.$message.error('提交失败，请重试')
      }
    },

    // 上传成功
    handleAvatarSuccess(res, file, filelist, index) {
      this.imageUrl.push(URL.createObjectURL(file.raw))
      this.optionList[index].img = this.imageUrl[this.imageUrl.length - 1]
      this.imageUrl.pop()
      console.log(res, filelist)
    },
    closeImage(index, e) {
      e.stopPropagation()
      this.optionList[index].img = ''
    }
  },
  mounted() {
    hljs.configure({
      // optionally configure hljs
      languages: ['javascript', 'java', 'python']
    })

    // 初始化功能
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'], // 切换按钮
      [{ list: 'ordered' }, { list: 'bullet' }], // 有序/无序列表
      ['blockquote'], // 文本块/代码块
      ['code-block', 'image', 'link'] // 图片 / 链接 / 视频
    ]
    // 挂载
    this.$nextTick(() => {
      this.quills1 = new Quill('#question', {
        modules: {
          toolbar: toolbarOptions,
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        },
        theme: 'snow' // 使用主题样式
      })
      this.quills2 = new Quill('#answer', {
        modules: {
          toolbar: toolbarOptions,
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        },
        theme: 'snow' // 使用主题样式
      })

      this.quills2.setContents([{ insert: this.answer }])
      this.quills1.setContents([{ insert: this.question }])
    })
  }
}
</script>

<style scoped lang="scss">
.dashboard-container {
  .app-container {
    .province {
      margin-right: 4px;
    }
    ::v-deep.ql-toolbar {
      height: 38px;
      padding-top: 0;
    }
    .question,
    .answer {
      width: 100%;
      height: 201px;
    }

    ::v-deep.option_item {
      margin-bottom: 20px;
      .optionRadio {
        margin-right: 0;
      }

      .optionsCheckbox {
        // display: block;
        margin-bottom: 20px !important;
      }
    }

    .avatar-uploader {
      display: inline-block;
      border: 1px dashed #d9d9d9;
      cursor: pointer;
      border-radius: 6px;
      position: relative;
      // top: 24px;
      left: 6px;
      // overflow: hidden;
      width: 100px;
      height: 60px;
      line-height: 60px;
      text-align: center;
      .avatar-uploader-text {
        font-size: 14px;
        color: #8c939d;
      }

      .avatar-close {
        position: absolute;
        top: -6px;
        right: -6px;
        // z-index: 9999999;
        font-size: 16px;
      }

      .avatar {
        position: absolute;
        top: 0;
        left: 0;
        width: 98px;
        height: 58px;
      }
    }
  }
}
</style>
